package com.iteaj.iot.tools.db.sql;

import cn.hutool.core.util.ReflectUtil;
import com.iteaj.iot.tools.annotation.IotFieldMeta;
import com.iteaj.iot.tools.annotation.IotTableIdMeta;
import com.iteaj.iot.tools.db.DBMeta;
import com.iteaj.iot.tools.db.FieldMeta;
import com.iteaj.iot.tools.db.IdType;
import com.iteaj.iot.tools.db.ParamValue;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 居于sql的数据存储元信息
 */
public interface SqlMeta extends DBMeta {

//    IdWorker worker = new IdWorker(3, 3);

    /**
     * 表字段标识
     * @return
     */
    String getId();

    /**
     * id字段类型
     * @return
     */
    IdType getType();

    @Override
    default List<ParamValue> getParams(Object entity) {
        if(entity instanceof Map) {
            return resolveMapEntityParams((Map) entity);
        } else {
            List<ParamValue> parameterValue = new ArrayList<>();

            for (int i=0; i< this.getFieldMetas().size(); i++) {
                FieldMeta meta = this.getFieldMetas().get(i);
                Field field;
                if(meta instanceof IotFieldMeta) {
                    field = ((IotFieldMeta) meta).getField();
                } else {
                    field = ((IotTableIdMeta) meta).getField();
                }

                Object value = ReflectUtil.getFieldValue(entity, field);
                parameterValue.add(new ParamValue(meta, value));
            }

            return parameterValue;
        }
    }

    default List<ParamValue> resolveMapEntityParams(Map mapEntity) {
        List<? extends FieldMeta> fieldMetas = getFieldMetas();
        List<ParamValue> parameterValues = new ArrayList<>();

        fieldMetas.forEach(item -> {
            Object value = mapEntity.get(item.getName());
            parameterValues.add(new ParamValue(item, value));
        });

        return parameterValues;
    }
}
